package com.binance.assetservice.web.health;

import com.binance.assetservice.vo.request.product.FetchProductsRequest;
import com.binance.assetservice.vo.response.product.FetchProductsResponse;
import com.binance.assetservice.web.controller.ProductController;
import com.binance.master.enums.LanguageEnum;
import com.binance.master.enums.TerminalEnum;
import com.binance.master.models.APIRequest;
import com.binance.master.models.APIResponse;
import com.binance.master.utils.TrackingUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

import java.util.List;
/**
 * 增加对getproduct接口的healthcheck
 * */
@Component
public class GetProductHealthIndicator implements HealthIndicator {
    @Autowired
    private ProductController productController;

    @Override
    public Health health() {
        Health.Builder builder = new Health.Builder();
        APIRequest<FetchProductsRequest> originRequest = new APIRequest<>();
        originRequest.setLanguage(LanguageEnum.ZH_CN);
        originRequest.setTerminal(TerminalEnum.WEB);
        originRequest.setTrackingChain(TrackingUtils.getTrackingChain());
        try {
            APIResponse<List<FetchProductsResponse>> apiResponse = productController.fetchProducts(APIRequest.instance(originRequest, new FetchProductsRequest()));
            if ((APIResponse.Status.ERROR == apiResponse.getStatus()) || CollectionUtils.isEmpty(apiResponse.getData())) {
                String errorMessage = "productController.fetchProducts:failed" +
                        ",error=" + apiResponse.getErrorData();
                builder.withDetail("errorMessage", errorMessage);
                return builder.down().build();
            }
        } catch (Exception e) {
            return builder.down(e).build();
        }
        return builder.up().build();
    }
}
